from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
from django.db.models import Sum
import re

class SparePartCategory(models.Model):
    """备件分类"""
    name = models.CharField(max_length=100, verbose_name='分类名称')
    description = models.TextField(blank=True, verbose_name='分类描述')
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, 
                             related_name='subcategories', verbose_name='父分类')
    
    class Meta:
        verbose_name = '备件分类'
        verbose_name_plural = '备件分类'
        ordering = ['name']

    def __str__(self):
        return self.name


class Supplier(models.Model):
    """供应商管理"""
    name = models.CharField(max_length=200, verbose_name='供应商名称')
    contact_person = models.CharField(max_length=100, blank=True, verbose_name='联系人')
    phone = models.CharField(max_length=20, blank=True, verbose_name='联系电话')
    email = models.EmailField(blank=True, verbose_name='邮箱')
    address = models.TextField(blank=True, verbose_name='地址')
    notes = models.TextField(blank=True, verbose_name='备注')
    
    class Meta:
        verbose_name = '供应商'
        verbose_name_plural = '供应商'
        ordering = ['name']

    def __str__(self):
        return self.name


class SparePart(models.Model):
    """备件基本信息"""
    # 备件状态选择
    STATUS_CHOICES = (
        ('active', '正常'),
        ('discontinued', '停产'),
        ('obsolete', '淘汰'),
    )
    
    name = models.CharField(max_length=200, verbose_name='备件名称')
    model = models.CharField(max_length=100, verbose_name='型号规格')
    part_number = models.CharField(max_length=100, unique=True, verbose_name='备件编号')
    category = models.ForeignKey(SparePartCategory, on_delete=models.SET_NULL, 
                                null=True, blank=True, verbose_name='分类')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    
    # 供应商信息
    supplier = models.ForeignKey(Supplier, on_delete=models.SET_NULL, 
                                null=True, blank=True, verbose_name='供应商')
    supplier_part_number = models.CharField(max_length=100, blank=True, verbose_name='供应商编号')
    
    # 技术参数
    specifications = models.TextField(blank=True, verbose_name='技术规格')
    unit = models.CharField(max_length=20, default='个', verbose_name='单位')
    unit_price = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='单价')
    
    # 库存预警
    min_stock = models.PositiveIntegerField(default=0, verbose_name='最低库存')
    max_stock = models.PositiveIntegerField(default=0, verbose_name='最高库存')
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    # 备注
    notes = models.TextField(blank=True, verbose_name='备注')
    
    class Meta:
        verbose_name = '备件'
        verbose_name_plural = '备件'
        ordering = ['name']

    def __str__(self):
        return f"{self.part_number} - {self.name} ({self.model})"

    @property
    def current_stock(self):
        """获取当前库存数量"""
        # 只计算入库记录的数量（operation_type='in'）
        total_in = self.inventory_records.filter(operation_type='in').aggregate(
            total=Sum('quantity'))['total'] or 0
        
        # 只计算出库记录的数量（operation_type='out'）
        total_out = self.inventory_records.filter(operation_type='out').aggregate(
            total=Sum('quantity'))['total'] or 0
        
        return total_in - total_out

    @property
    def stock_status(self):
        """库存状态"""
        current = self.current_stock
        if current <= self.min_stock:
            return 'low'
        elif current >= self.max_stock > 0:
            return 'high'
        else:
            return 'normal'

    def is_low_stock(self):
        """是否库存不足"""
        return self.current_stock <= self.min_stock

    def is_over_stock(self):
        """是否库存过高"""
        return self.max_stock > 0 and self.current_stock >= self.max_stock


class InventoryRecord(models.Model):
    """库存记录（入库/出库）"""
    # 操作类型
    OPERATION_CHOICES = (
        ('in', '入库'),
        ('out', '出库'),
        ('adjust', '调整'),
    )
    
    spare_part = models.ForeignKey(SparePart, on_delete=models.CASCADE, 
                                  related_name='inventory_records', verbose_name='备件')
    operation_type = models.CharField(max_length=10, choices=OPERATION_CHOICES, verbose_name='操作类型')
    quantity = models.IntegerField(validators=[MinValueValidator(1)], verbose_name='数量')
    
    # 关联信息
    related_order = models.ForeignKey('PurchaseOrder', on_delete=models.SET_NULL, 
                                     null=True, blank=True, verbose_name='关联采购单')
    related_usage = models.ForeignKey('UsageRecord', on_delete=models.SET_NULL, 
                                     null=True, blank=True, verbose_name='关联使用记录')
    
    # 操作信息
    operator = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, 
                               related_name='inventory_operations', verbose_name='操作人')
    operation_date = models.DateTimeField(auto_now_add=True, verbose_name='操作时间')
    notes = models.TextField(blank=True, verbose_name='备注')
    
    class Meta:
        verbose_name = '库存记录'
        verbose_name_plural = '库存记录'
        ordering = ['-operation_date']

    def __str__(self):
        return f"{self.spare_part.name} - {self.get_operation_type_display()} - {self.quantity}"


class UsageRecord(models.Model):
    """备件使用记录"""
    spare_part = models.ForeignKey(SparePart, on_delete=models.CASCADE, 
                                  related_name='usage_records', verbose_name='备件')
    quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)], verbose_name='使用数量')
    
    # 关联工单
    ticket = models.ForeignKey('tickets.Ticket', on_delete=models.CASCADE, 
                             null=True, blank=True, verbose_name='关联工单')
    
    # 关联维修记录
    maintenance_record = models.ForeignKey('tickets.MaintenanceRecord', on_delete=models.CASCADE,
                                         null=True, blank=True, related_name='spare_part_usage', 
                                         verbose_name='关联维修记录')
    
    # 使用信息
    used_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, 
                              related_name='spare_part_usage', verbose_name='使用人')
    used_at = models.DateTimeField(auto_now_add=True, verbose_name='使用时间')
    purpose = models.TextField(verbose_name='用途说明')
    
    class Meta:
        verbose_name = '使用记录'
        verbose_name_plural = '使用记录'
        ordering = ['-used_at']

    def __str__(self):
        return f"{self.spare_part.name} - {self.quantity} - {self.used_by}"


class PurchaseOrder(models.Model):
    """采购订单"""
    # 订单状态
    STATUS_CHOICES = (
        ('draft', '草稿'),
        ('submitted', '已提交'),
        ('approved', '已批准'),
        ('ordered', '已订购'),
        ('received', '已收货'),
        ('cancelled', '已取消'),
    )
    
    order_number = models.CharField(max_length=50, unique=True, verbose_name='订单编号')
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, verbose_name='供应商')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='draft', verbose_name='状态')
    
    # 订单信息
    total_amount = models.DecimalField(max_digits=12, decimal_places=2, default=0, verbose_name='总金额')
    order_date = models.DateField(null=True, blank=True, verbose_name='订购日期')
    expected_delivery = models.DateField(null=True, blank=True, verbose_name='预计到货')
    actual_delivery = models.DateField(null=True, blank=True, verbose_name='实际到货')
    
    # 审批信息
    requested_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True,
                                   related_name='purchase_requests', verbose_name='申请人')
    approved_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True,
                                   related_name='approved_orders', verbose_name='审批人')
    approved_at = models.DateTimeField(null=True, blank=True, verbose_name='审批时间')
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    # 备注
    notes = models.TextField(blank=True, verbose_name='备注')
    
    class Meta:
        verbose_name = '采购订单'
        verbose_name_plural = '采购订单'
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.order_number} - {self.supplier.name}"

    def save(self, *args, **kwargs):
        if not self.order_number:
            self.order_number = self.generate_order_number()
        super().save(*args, **kwargs)

    def generate_order_number(self):
        """生成订单编号: PO-年月日-序号"""
        from django.utils import timezone
        date_str = timezone.now().strftime('%Y%m%d')
        
        # 查找当天的最大序号
        existing_orders = PurchaseOrder.objects.filter(
            order_number__startswith=f'PO-{date_str}'
        )
        
        max_number = 0
        for order in existing_orders:
            try:
                parts = order.order_number.split('-')
                if len(parts) == 3:
                    number = int(parts[2])
                    max_number = max(max_number, number)
            except (ValueError, IndexError):
                continue
        
        new_number = max_number + 1
        return f"PO-{date_str}-{new_number:03d}"

    @property
    def items_count(self):
        """订单项数量"""
        return self.order_items.count()


class PurchaseOrderItem(models.Model):
    """采购订单项"""
    order = models.ForeignKey(PurchaseOrder, on_delete=models.CASCADE, 
                            related_name='order_items', verbose_name='采购订单')
    spare_part = models.ForeignKey(SparePart, on_delete=models.CASCADE, verbose_name='备件')
    quantity = models.PositiveIntegerField(validators=[MinValueValidator(1)], verbose_name='数量')
    unit_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='单价')
    received_quantity = models.PositiveIntegerField(default=0, verbose_name='已收货数量')
    
    class Meta:
        verbose_name = '采购订单项'
        verbose_name_plural = '采购订单项'

    def __str__(self):
        return f"{self.order.order_number} - {self.spare_part.name}"

    @property
    def total_price(self):
        """单项总价"""
        return self.quantity * self.unit_price

    @property
    def is_fully_received(self):
        """是否完全收货"""
        return self.received_quantity >= self.quantity
